我想问一下是否可以在模板参数中插入静态断言。
假设我想创建类,StaticArray<T,N>并且我想让用户无法实例化大小等于 0 的类。有什么办法可以static_assert(N != 0, "error message")在我的类中插入类似的东西?
#include <iostream>
using namespace std;
template <int fact>
constexpr int pow2T()
{
static_assert(fact < 0, "error");
return fact == 0 ? 1 : pow2T<fact - 1>() * 2;
}
constexpr int e2 = pow2T<2>();
int main(int argc, char *argv[])
{
cout << e2 << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试x^2使用参数静态检查实现静态计算.断言失败..为什么!?
/home/serj/work/untitled/main.cpp:-1:在函数'constexpr int pow2T()[with int fact = 2]'中:
/home/serj/work/untitled/main.cpp:-1:在函数'constexpr int pow2T()[with int fact = 1]'中:
...
以下不编译:
template<typename... Args>
void check_format(Args&&... args)
{
static_assert((true && std::is_fundamental<decltype(args)>::value)...);
}
Run Code Online (Sandbox Code Playgroud) 请考虑以下代码:
void f(auto& i, auto& j)
{
static_assert(/* SOMETHING */, "");
// function body here...
}
Run Code Online (Sandbox Code Playgroud)
我希望该/* SOMETHING */部件检查以下代码是否编译(考虑所有标准规则,如隐式转换规则):
i += j;
Run Code Online (Sandbox Code Playgroud)
我试过了:
sizeof(std::declval<decltype(i)>() += std::declval<decltype(j)>());
Run Code Online (Sandbox Code Playgroud)
但它失败了.
这样做的正确方法是什么?
编辑:我了解SFINAE和约束模板参数.这不是问题的主题.主题是static_assert在测试表达式的正确性时如何使失败.
(为标题笨拙而道歉;我不知道如何更简洁地概括这个问题。如果有人有更好的主意,请随时进行编辑!)
我想编写一个自由函数,该函数可以基于类的成员函数的返回值自动确定其参数的类型。使用decltype,这部分很容易。
我还希望有一个编译时断言来验证关于该参数类型的假设,这就是我提出的解决方案的地方。
考虑以下MCVE:
#include <type_traits>
#include <array>
#include <iostream>
class Foo
{
public:
std::array<int, 10> Get();
};
void PrintFoos(const decltype(Foo().Get())& param)
{
static_assert(param.size() == 10, "wrong size");
for (const auto& i : param)
{
std::cout << i << "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
GCC可以很好地编译以上代码,但不会发出警告。
另一方面,lang声抓住:
error: static_assert expression is not an integral constant expression
static_assert(param.size() == 10, "wrong size");
^~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
MSVC也是如此:
(13): error C2131: expression did not evaluate to a constant
(13): note: failure was caused by …Run Code Online (Sandbox Code Playgroud) 为什么类定义中的 this (static_assert) 不起作用?
template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");
};
int _tmain(int argc, _TCHAR* argv[])
{
int low, high;
X<char,1,'a'> x;//HERE I SHOULD GET ERROR
cout << sizeof(x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)