[英]Specialize if value of a variable is known/unknown at compile time
如何專門化模板 function,以應對其參數之一的值在編譯期間(在實際編譯和運行程序之前)已知/未知的情況?
我還不知道怎么做。
想法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
想法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.
好吧,我想你的意思是論證的類型 ,對吧? 部分模板專業化的值無關緊要......
然后:這不可能。
必須在編譯時知道模板的參數類型。 編譯器還應該如何生成正確的代碼?
此外,對於部分模板特化,由於相同的原因,必須在編譯時知道類型。
我參加派對有點晚了,我的部分回答可能不是很令人滿意,但這里是:
我們無法通過檢查判斷某個值在編譯時是否已知的情況:
constexpr
函數的非模板輸入值 我不知道如何處理問題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;
示例使用:
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>);
}
演示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.