template <int answer> struct Hitchhiker {
static_assert(sizeof(answer) != sizeof(answer), "Invalid answer");
};
template <> struct Hitchhiker<42> {};
Run Code Online (Sandbox Code Playgroud)
在尝试禁用常规模板实例化的同时,static_assert我发现clang即使模板未实例化,上面的代码也会生成断言错误,而gcc只有在Hitchhiker使用除了以外的参数进行实例化时才生成断言错误42.
摆弄我发现这个断言:
template <int answer> struct Hitchhiker {
static_assert(sizeof(int[answer]) != sizeof(int[answer]), "Invalid answer");
};
template <> struct Hitchhiker<42> {};
Run Code Online (Sandbox Code Playgroud)
两个编译器的行为相同:只有在实例化通用模板时,断言才会启动.
标准说什么,哪个编译器是对的?
g++ 4.9.2
clang++ 3.50
Run Code Online (Sandbox Code Playgroud) 我继承了一些看起来像这样的代码:
///
/// A specializable function for converting a user-defined object to a string value
///
template <typename value_type>
std::string to_string(const value_type &value)
{
static_assert(!std::is_same<value_type, value_type>::value, "Unspecialized usage of to_string not supported");
return "";
}
///
/// A specializable function for converting a user-defined object from a string to a value
///
template <typename return_type>
return_type from_string(const std::string &source)
{
static_assert(!std::is_same<return_type, return_type>::value, "Unspecialized usage of from_string not supported");
}
Run Code Online (Sandbox Code Playgroud)
!std::is_same<value_type, value_type>::value 看起来过于冗长.
我应该将这些陈述改为static_assert(false,"...")吗?
我不确定它是否以这种方式表达来处理某种边缘情况,或者false确实是等效的.
std::is_same<t,t>::value永远是真的吗?