我一直在研究模板,并希望强制给函数的模板类型具有特定的静态成员。不幸的是,没有std::is_static类型特征。
我将如何使用它的粗略示例(或替代方法):
template<typename T>
void SomeFunc(T& obj)
{
static_assert(std::is_static_v<decltype(T::someVariable)>, "someVariable must be static");
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以实现这种行为?我可以写
template<typename T>
void SomeFunc(T& obj)
{
// must be static
T::someVariable;
}
Run Code Online (Sandbox Code Playgroud)
但这不会像static_assert带有体面的消息那样好听或有用。这只是一种语法错误:(
谢谢!
以下编译在VS2017中很好:
#include <type_traits>
struct Foo
{
int bar;
};
int main()
{
static_assert(std::is_same_v<decltype(Foo::bar), int>, "Foo::bar isn't an int");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果Foo :: bar的访问在编译时没有强制它是Foo的静态成员吗?我试图强制模板类型的特定成员变量是静态的时偶然发现了这一点.