相关疑难解决方法(0)

即使模板函数无处调用,static_assert也无法编译

我使用g ++ 4.6.3(目前是ubuntu 12.04的默认包),标志为c ++ 0x,我偶然发现:

template <typename T>
inline T getValue(AnObject&)
{
    static_assert(false , "this function has to be implemented for desired type");
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

static_assertion failed "this function has to be implemented for the desired type"
Run Code Online (Sandbox Code Playgroud)

即使我还没有在任何地方调用此功能.

这是一个g ++错误吗?只有在代码中的某处调用此函数时,才应该实现此函数.

c++ templates g++ static-assert c++11

33
推荐指数
3
解决办法
1万
查看次数

解决静态断言中的不完整类型

当表达式取决于类类型本身时,有没有办法在类内进行 static_assert ?也许延迟评估直到类型完成或模板实例化之后?

示例代码:

#include <type_traits>

template<typename T>
struct Test {
   T x = 0; // make non-trivial
   static_assert(std::is_trivial<Test<T>>::value, "");
};

int main() {
    // would like static assert failure, instead get 'incomplete type' error
    Test<int> test1;
    Test<float> test2;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ templates static-assert type-traits

6
推荐指数
1
解决办法
977
查看次数

标签 统计

c++ ×2

static-assert ×2

templates ×2

c++11 ×1

g++ ×1

type-traits ×1