如果模板从未在未评估的上下文之外被调用,是否返回declvalUB?
我正在编写一些元函数,并且我有想法使用 C++17 的 if constexpr 结合推导的返回类型来编写它们。这是一个例子:
#include <tuple>
#include <type_traits>
#include <string>
template<typename TupleType, std::size_t I = 0, typename... ReturnData>
constexpr auto filterImpl()
{
if constexpr (I < std::tuple_size_v<TupleType>)
{
using Type = std::tuple_element_t<I, TupleType>;
if constexpr (std::is_arithmetic_v<Type>)
return filterImpl<TupleType, I + 1, ReturnData..., Type>();
else
return filterImpl<TupleType, I + 1, ReturnData...>();
}
else
return std::declval<std::tuple<ReturnData...>>();
}
template<typename Tuple>
using FilterTuple = decltype(filterImpl<Tuple>());
//std::tuple<int, float>
using MyTuple = FilterTuple<std::tuple<int, std::string, float, int*>>;
int main(int argc, char* argv[])
{
MyTuple t{ 3, 5.f };
return 0;
}
当然,您可能可以使用更简单的模式来解决这个问题,但这只是我想要做的一个基本示例。
此代码在 msvc 上编译,但不在 onlinegdb 上编译。哪一个是对的?以这种方式使用 declval 是否获得授权?我应该像这样编写元函数,还是应该回到模板类?
(我认为,如果有办法这样做,更复杂的元函数最终可能会更容易阅读)
一个mcve:
#include <utility>
template<bool b>
constexpr auto evil()
{
if constexpr (b)
return 0;
else
return std::declval<int>();
}
template<bool b>
using Test = decltype(evil<b>());
int main()
{
Test<false> t{};
}