C++ C++;17为模板函数参数调用结果和静态断言
这纯粹是为了在进行泛型编程时获得更多的知识。如何确保将函数的返回类型作为模板参数传递给另一个函数,该函数可以采用不同数量的参数(0到N) 编辑: 我试图使用C++ C++;17为模板函数参数调用结果和静态断言,c++,templates,variadic-templates,c++17,static-assert,C++,Templates,Variadic Templates,C++17,Static Assert,这纯粹是为了在进行泛型编程时获得更多的知识。如何确保将函数的返回类型作为模板参数传递给另一个函数,该函数可以采用不同数量的参数(0到N) 编辑: 我试图使用std::invoke_result和static_assert()来确保注册工厂方法的正确返回类型。我用了一个比第一篇文章更好的例子来说明问题 #include <string> #include <memory> #include <typeindex> #include <typeinfo>
std::invoke_result
和static_assert()
来确保注册工厂方法的正确返回类型。我用了一个比第一篇文章更好的例子来说明问题
#include <string>
#include <memory>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
using namespace std;
class Factory final
{
public:
template<typename My_Type, typename Func>
static bool Register(Func func)
{
// issue is these two lines of code, when trying to register Derived1 and Derived2 create functions
typename invoke_result<Func>::type result;
static_assert(is_same<decltype(result), unique_ptr<My_Type>>::value, "Not a unique pointer to type 'My_Type'");
bool isRegistered = false;
if (GetCreateFunctions().end() == GetCreateFunctions().find(typeid(My_Type)))
{
GetCreateFunctions()[typeid(My_Type)] = reinterpret_cast<void*>(func);
isRegistered = true;
}
return isRegistered;
}
template<typename My_Type, typename... Args>
static unique_ptr<My_Type> Create(Args&&... args)
{
unique_ptr<My_Type> type = nullptr;
auto iter = GetCreateFunctions().find(typeid(My_Type));
if (GetCreateFunctions().end() != iter)
{
typedef unique_ptr<My_Type>(*create_func)(Args&&...);
auto create = reinterpret_cast<create_func>(iter->second);
type = create(forward<Args>(args)...);
}
return type;
}
private:
static unordered_map<type_index, void*>& GetCreateFunctions()
{
static unordered_map<type_index, void*> map;
return map;
}
};
class Base
{
public:
Base(unique_ptr<string>&& moveString)
:
_moveString(move(moveString))
{
}
virtual ~Base() = default;
virtual void DoSomething() const = 0;
protected:
unique_ptr<string> _moveString;
};
class Derived1 final : public Base
{
public:
Derived1(unique_ptr<string>&& moveString)
:
Base(move(moveString))
{
}
~Derived1() = default;
void DoSomething() const override
{
if (_moveString)
{
// do something...
}
}
private:
static const bool _isRegistered;
static unique_ptr<Derived1> Create(unique_ptr<string>&& moveString)
{
return make_unique<Derived1>(move(moveString));
}
};
const bool Derived1::_isRegistered = Factory::template Register<Derived1>(&Derived1::Create);
class Derived2 final : public Base
{
public:
Derived2()
:
Base(make_unique<string>("Default"))
{
}
~Derived2() = default;
void DoSomething() const override
{
if (_moveString)
{
// do something...
}
}
private:
static const bool _isRegistered;
static unique_ptr<Derived2> Create()
{
return make_unique<Derived2>();
}
};
const bool Derived2::_isRegistered = Factory::template Register<Derived2>(&Derived2::Create);
int main(int argc, char** argv)
{
string moveString = "moveString";
unique_ptr<Base> myBase_Derived1 = Factory::template Create<Derived1>(make_unique<string>(move(moveString)));
unique_ptr<Base> myBase_Derived2 = Factory::template Create<Derived2>();
if (myBase_Derived1)
printf("Success\n");
if (myBase_Derived2)
printf("Success\n");
return 0;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
班级工厂决赛
{
公众:
模板
静态布尔寄存器(Func Func)
{
//问题是,在尝试注册Derived1和Derived2创建函数时,这两行代码是错误的
typename调用_结果::类型结果;
静态断言(is_same::value,“不是指向类型‘My_type’的唯一指针”);
bool isRegistered=false;
if(GetCreateFunctions().end()==GetCreateFunctions().find(typeid(My_类型)))
{
GetCreateFunctions()[typeid(My_Type)]=重新解释强制转换(func);
isRegistered=真;
}
已登记退货;
}
模板
静态唯一\u ptr创建(Args&&…Args)
{
唯一_ptr type=nullptr;
auto iter=GetCreateFunctions().find(typeid(My_Type));
if(GetCreateFunctions().end()!=iter)
{
typedef unique_ptr(*create_func)(参数和;
自动创建=重新解释(iter->秒);
类型=创建(正向(参数)…);
}
返回类型;
}
私人:
静态无序映射&GetCreateFunctions()
{
静态无序图;
返回图;
}
};
阶级基础
{
公众:
基本(唯一的\u ptr&&moveString)
:
_移动字符串(移动(移动字符串))
{
}
virtual~Base()=默认值;
虚拟void DoSomething()常量=0;
受保护的:
唯一的\u ptr\u移动字符串;
};
派生类1最终版:公共基础
{
公众:
Derived1(唯一\u ptr&&moveString)
:
基本(移动(移动字符串))
{
}
~Derived1()=默认值;
void DoSomething()常量重写
{
if(_moveString)
{
//做点什么。。。
}
}
私人:
静态常数布尔值已注册;
静态唯一\u ptr创建(唯一\u ptr&&moveString)
{
返回make_unique(move(moveString));
}
};
const bool Derived1::_isRegistered=Factory::template Register(&Derived1::Create);
衍生类2最终版:公共基础
{
公众:
衍生2()
:
基本(使_唯一(“默认”))
{
}
~Derived2()=默认值;
void DoSomething()常量重写
{
if(_moveString)
{
//做点什么。。。
}
}
私人:
静态常数布尔值已注册;
静态唯一\u ptr Create()
{
返回make_unique();
}
};
const bool Derived2::_isRegistered=Factory::template Register(&Derived2::Create);
int main(int argc,字符**argv)
{
string moveString=“moveString”;
unique_ptr myBase_Derived1=工厂::模板创建(使_唯一(移动(移动字符串));
unique_ptr myBase_Derived2=工厂::模板创建();
如果(myBase_Derived1)
printf(“成功”\n);
如果(myBase_Derived2)
printf(“成功”\n);
返回0;
}
您有一个额外的()
static_assert(std::is_same<decltype(result), std::unique_ptr<T>/* here */ >::value, "Not a unique pointer to type 'T'");
这并不是在所有函数情况下都有效,但是,对于函数指针,它应该可以工作 如果您按照以下方式定义自定义模板
template <typename>
struct baz;
template <typename R, typename ... Args>
struct baz<R(*)(Args...)>
{ using retType = R; };
或者,在Register()方法中
template<typename My_Type, typename Func>
static bool Register(Func func)
{
static_assert(std::is_same<
typename decltype(std::function{func})::result_type,
std::unique_ptr<My_Type>>::value, "!");
bool isRegistered = false;
if (GetCreateFunctions().end() == GetCreateFunctions().find(typeid(My_Type)))
{
GetCreateFunctions()[typeid(My_Type)] = reinterpret_cast<void*>(func);
isRegistered = true;
}
return isRegistered;
}
模板
静态布尔寄存器(Func Func)
{
静态断言(std::是否相同<
typename decltype(std::function{func})::结果类型,
std::unique_ptr>::value,“!”;
bool isRegistered=false;
if(GetCreateFunctions().end()==GetCreateFunctions().find(typeid(My_类型)))
{
GetCreateFunctions()[typeid(My_Type)]=重新解释强制转换(func);
isRegistered=真;
}
已登记退货;
}
感谢您的回复,它适用于发布的原始代码。但这不是我想要的。我发布了一个基于注册工厂的更直接的代码示例,我认为通过确保返回类型与“Register”方法的模板类型匹配,该示例将受益。@希腊语作为一般规则,如果有人回答提出的问题,请向上投票,勾选标记。如果你真正的问题是其他问题,在原问题解决后再创建一个新问题。仔细检查是否是一个。@Adam Nevraumont我下次会这样做。我认为最初的示例足够“最小”,但结果不是…模板无效示例(Func){//Func可以有参数,也可以没有参数静态_断言(std::is_same::value,“不是指向类型“T”的唯一指针);}请不要完全重写已经回答的问题。问一个新问题。@Adam Nevraumont下次会问。谢谢max66,我更改了代码示例以更好地说明我的问题。有一个工厂的“Register”方法存在静态_断言问题。@GreekFire-无法复制:对我来说有效;尝试使用静态断言(std::is_same::value,“!”)代码>;给我几分钟,我提出另一个(仅限C++17)解决方案;但是这一个应该也适用于您Register()
@GreekFire-第二个(仅限C++17)解决方案改进了答案;对我来说,这两种方法都适用于你的代码。哇,c++17解决方案很好用。。。工作得很好!(对于Register()方法)@GreekFire-极大的改进C++17演绎指南!
template <typename>
struct baz;
template <typename R, typename ... Args>
struct baz<R(*)(Args...)>
{ using retType = R; };
template <typename T, typename Func>
void Example(Func func)
{
static_assert(std::is_same<typename baz<Func>::retType,
std::unique_ptr<T>>::value, "!");
}
#include <type_traits>
#include <memory>
template <typename>
struct baz;
template <typename R, typename ... Args>
struct baz<R(*)(Args...)>
{ using retType = R; };
template <typename T, typename Func>
void Example(Func func)
{
static_assert(std::is_same<typename baz<Func>::retType,
std::unique_ptr<T>>::value, "!");
}
struct Foo
{
Foo (int i) : My_I{i}
{ }
Foo () : My_I{99}
{ }
~Foo() = default;
int My_I;
};
std::unique_ptr<Foo> bar0 ()
{ return std::make_unique<Foo>(11); }
std::unique_ptr<Foo> bar1 (int)
{ return std::make_unique<Foo>(11); }
std::unique_ptr<Foo> bar2 (int, long)
{ return std::make_unique<Foo>(11); }
int main ()
{
Example<Foo>(&bar0);
Example<Foo>(&bar1);
Example<Foo>(&bar2);
}
template <typename T, typename Func>
void Example(Func func)
{
static_assert(std::is_same<
typename decltype(std::function{func})::result_type,
std::unique_ptr<T>>::value, "!");
}
template<typename My_Type, typename Func>
static bool Register(Func func)
{
static_assert(std::is_same<
typename decltype(std::function{func})::result_type,
std::unique_ptr<My_Type>>::value, "!");
bool isRegistered = false;
if (GetCreateFunctions().end() == GetCreateFunctions().find(typeid(My_Type)))
{
GetCreateFunctions()[typeid(My_Type)] = reinterpret_cast<void*>(func);
isRegistered = true;
}
return isRegistered;
}