[英]Specialize if value of a variable is known/unknown at compile time
How to specialize a template function for the case that the value of one of its argument is known/unknown during compile time (before actually compile and run the program)?如何专门化模板 function,以应对其参数之一的值在编译期间(在实际编译和运行程序之前)已知/未知的情况?
I can't figure out how yet.我还不知道怎么做。
idea 1:想法1:
#include <type_traits>
#include <iostream>
int main(void){
int a; //value of a is not known at compile time
bool b = (a == a); //value of b is known at compile time.
std::is_assignable< constexpr bool, bool >::value
}
//g++ magic.cpp -std=c++14
//error: wrong number of template arguments (1, should be 2)
// std::is_assignable< constexpr bool, bool >::value
Idea 2:想法2:
#include <type_traits>
#include <iostream>
int main(void){
const int a=1;
int b = (a == a);
std::cout << __builtin_constant_p (a) << std::endl;
std::cout << __builtin_constant_p (b) << std::endl;
}
//prints 0 and 0.
Well, I guess you mean the type of the argument, right? 好吧,我想你的意思是论证的类型 ,对吧? Values don't matter for partial template specializations...
部分模板专业化的值无关紧要......
Then: This can't be done. 然后:这不可能。
Parameter types for templates must be known at compile time. 必须在编译时知道模板的参数类型。 How else should the compiler produce the correct code?
编译器还应该如何生成正确的代码?
Also for partial template specializations, the types must be known at compile time for the same reason. 此外,对于部分模板特化,由于相同的原因,必须在编译时知道类型。
I'm a bit late to the party, and my partial answer may not be very satisfying, but here goes:我参加派对有点晚了,我的部分回答可能不是很令人满意,但这里是:
Situations where we can't tell from inspection whether a value is known at compile time:我们无法通过检查判断某个值在编译时是否已知的情况:
constexpr
functions constexpr
函数的非模板输入值 I don't know what to do about problem 1
, but for problem 2
we can use SFINAE
: looking for a specific member with known name (in the below example it's X
), and trying to send it as a template argument, like so:我不知道如何处理问题
1
,但对于问题2
,我们可以使用SFINAE
:查找具有已知名称的特定成员(在下面的示例中为X
),并尝试将其作为模板参数发送,如下所示:
// like std::void_t, but for value inputs:
template <auto>
using v_to_void_t = void;
//////////////////////////////////////////////////////////////
template <class, class = void>
struct has_constexpr_X
: std::false_type {};
template <class T>
struct has_constexpr_X <T, v_to_void_t<T().X>>
: std::true_type {};
template <class T>
constexpr bool has_constexpr_X_v
= has_constexpr_X<T>::value;
Example uses:示例使用:
struct HasStaticConstexprX {
static constexpr int X = 2;
};
struct HasStaticConstX {
static const int X; // implied constexpr
};
const int HasStaticConstX::X = 3;
struct HasStaticX {
static int X;
};
int HasStaticX::X = 4;
struct HasConstX {
const int X;
};
int main () {
static_assert(has_constexpr_X_v<HasStaticConstexprX>);
static_assert(has_constexpr_X_v<HasStaticConstX>);
static_assert(! has_constexpr_X_v<HasStaticX>);
static_assert(! has_constexpr_X_v<HasConstX>);
}
Demos:演示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.