【发布时间】:2016-09-27 12:44:58
【问题描述】:
我想在编译时检查是否为类型 Ret 和参数 Arg 定义了用户文字 _name。虽然我有一半的解决方案,但它需要至少定义一次文字 operator:
#include <iostream>
#include <type_traits>
struct one { };
struct two { };
// we need at least one of these definitions for template below to compile
one operator"" _x(char const*) {return {};}
two operator"" _x(unsigned long long int) {return {};}
template<class T, class S, class = void>
struct has_literal_x : std::false_type
{ };
template<class T, class S>
struct has_literal_x <T, S,
std::void_t<decltype((T(*)(S))(operator"" _x))>
> : std::true_type
{ };
int main()
{
std::cout << has_literal_x<one, char const*>::value << std::endl;
std::cout << has_literal_x<two, unsigned long long int>::value << std::endl;
std::cout << has_literal_x<one, unsigned long long int>::value << std::endl;
std::cout << has_literal_x<two, char const*>::value << std::endl;
std::cout << has_literal_x<int, char const*>::value << std::endl;
}
输出:
1
1
0
0
0
但是,如果没有至少一个定义可能重载的用户文字,则此解决方案将不起作用。有没有办法检查它,即使是不存在的文字(可能与我们检查类 X 是否有成员 member 的方法相同,但我不知道在这种情况下它是否可行)?
【问题讨论】:
标签: c++ templates sfinae c++17