Hat*_*ead 2 c++ static type-traits c++11
我一直在研究模板,并希望强制给函数的模板类型具有特定的静态成员。不幸的是,没有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带有体面的消息那样好听或有用。这只是一种语法错误:(
谢谢!
如果我正确理解了您想要的内容,那么您正在寻找std::is_member_pointer(或的值相反std::is_member_pointer)。
一个示例(也符合C ++ 11和C ++ 14)
#include <type_traits>
struct foo
{ int value; };
struct bar
{ static int value; };
int main()
{
static_assert(
true == std::is_member_pointer<decltype(&foo::value)>::value, "!");
static_assert(
false == std::is_member_pointer<decltype(&bar::value)>::value, "!!");
}
Run Code Online (Sandbox Code Playgroud)
-编辑-
不知道要理解nakiya的反对意见,但是...在以下示例中,我开发了类型traits(hasSomeValueStatic),该属性设置value为truetemplate参数是否具有someValue静态成员而false其他(如果someValue不是static,则不是)someValue。
#include <iostream>
#include <type_traits>
struct foo
{ int someValue; };
struct bar
{ static int someValue; };
template <typename, typename = int>
struct hasSomeValueStatic : std::false_type
{ };
template <typename T>
struct hasSomeValueStatic<T, decltype(T::someValue, 0)>
: std::integral_constant<bool,
! std::is_member_pointer<decltype(&T::someValue)>::value>
{ };
int main()
{
std::cout << hasSomeValueStatic<foo>::value << std::endl; // print 0
std::cout << hasSomeValueStatic<bar>::value << std::endl; // print 1
std::cout << hasSomeValueStatic<int>::value << std::endl; // print 0
}
Run Code Online (Sandbox Code Playgroud)