我想创建一个类专业化,如果它传递任何 std::variant 或任何 boost::variant,则具有相同的实现。我尝试使用 std::enable_if、std::disjunction 和 std::is_same 但无法编译它。这是一个代码示例来展示我想要实现的目标。
#include <variant>
#include <iostream>
#include <boost/variant.hpp>
template <typename T>
struct TypeChecker;
template <typename T>
struct TypeChecker<T>
{
void operator()()
{
std::cout << "I am other type\n";
}
}
template <typename ... Ts> // I want to be able to capture Ts... in TypeChecker scope
struct TypeChecker<std::variant<Ts...> or boost::variant<Ts...>> // what to insert here?
{
void operator()()
{
std::cout << "I am either std::variant or boost::variant\n";
}
}
int main()
{
TypeChecker<std::variant<int, float>>{}(); …Run Code Online (Sandbox Code Playgroud) 我正在阅读一种用于在同一对象中存储左值或右值的技术。请在此处找到对此的描述 。重载技巧已实现。
然而,当定义重载结构体时,会定义一个加法重载构造函数,其中将 lambda 衰减时生成的函数指针作为参数传递
template<typename... Functions>
struct overload : Functions...
{
using Functions::operator()...;
overload(Functions... functions) : Functions(functions)... {}
};
Run Code Online (Sandbox Code Playgroud)
为什么需要显式定义这个构造函数?
这里有一个现场演示。
使用cppinsights分析代码,上述代码的模板实例化如下
inline overload(__lambda_39_13 __functions0, __lambda_40_13 __functions1, __lambda_41_13 __functions2)
: __lambda_39_13(__functions0)
, __lambda_40_13(__functions1)
, __lambda_41_13(__functions2)
{
}
Run Code Online (Sandbox Code Playgroud)
我不清楚这个模板实例化是如何生成的。
使用显式自定义推导指南无法编译
看看下面修改后的演示
产生以下错误
:38:9: 错误: 没有匹配的函数来调用 'overload&) [with T = ...
这是我的结构,它在创建变量时使用隐式转换。
#include <string>
#include <variant>
using namespace std;
using val = variant<int, string, double, bool, long, long long, long double>;
struct value
{
val innerVal;
value():innerVal(""){}
value(const val &c) : innerVal(c) {}
template <typename T>
operator T()
{
return get<T>(innerVal);
}
template <typename V>
value &operator=(const V &t)
{
innerVal = t;
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
这就是我在构造变量时使用它的方式,它工作正常,但是当我分配一个已经创建的变量来value构造它时,它会给出错误。
int main(int argc, char* argv[])
{
value h;
h = "String";
string m = h;// Here works fine
string b = …Run Code Online (Sandbox Code Playgroud) 我有以下代码
procedure TfrmJsApplications.colMaintStylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
var
aColumn: TcxCustomGridTableItem;
aValue: Variant;
begin
inherited;
try
aColumn := Sender.FindItemByName('colApplication_Doc');
aValue := aRecord.Values[aColumn.Index];
if VarToStr(aValue) <> '' then
colMaint.Properties.Buttons[0].Caption := 'Redigere'
else
colMaint.Properties.Buttons[0].Caption := 'Opret'
except
on E:exception do
Logfile.Error('F_JsApplications.colMaintStylesGetContentStyle: ' + E.Message);
end;
Run Code Online (Sandbox Code Playgroud)
在cxGrid中的列上运行.但由于某种原因,我根本无法弄清楚这一行
if VarToStr(aValue) <> '' then
Run Code Online (Sandbox Code Playgroud)
使功能崩溃.我知道当aValue成为Null值时,但据我所知,在这种情况下VarToStr应返回''