是否有可能在编译时检查属于两个不同类的两个构造函数是否具有相同的签名? 如果有可能,如何实施呢?
示例:
struct A
{
A(int){}
};
struct B
{
B(int){}
};
int main()
{
static_assert(std::same_signature< A::A , B::B >::value, "A and B must have the same constructor parameters");
return 0;
}
答案 0 :(得分:1)
是否有可能在编译时检查属于两个不同类的两个构造函数是否具有相同的签名?
不完全符合您的要求,但您可以检查class A
和class B
是否可以
使用这种结构CheckConstructable<A, B, types...>::value
,c ++ 11:
#include <utility>
#include <string>
#include <type_traits>
#include <iostream>
struct A { A(int){} };
struct B { B(int){} B(std::string) {} };
struct C { C(std::string) {} };
template<class A, class B, typename... Types>
struct CheckConstructable;
template<class A, class B>
struct CheckConstructable<A, B> {
static constexpr bool value = false;
};
template<class A, class B, typename T1, typename... Types>
struct CheckConstructable<A, B, T1, Types...> {
static constexpr bool cur_type_ok = std::is_constructible<A, T1>::value && std::is_constructible<B, T1>::value;
static constexpr bool value = cur_type_ok || CheckConstructable<A, B, Types...>::value;
};
int main()
{
std::cout << "Have the same: " << (CheckConstructable<A, B, int, std::string>::value ? "yes" : "no") << "\n";
std::cout << "Have the same: " << (CheckConstructable<A, B, std::string>::value ? "yes" : "no") << "\n";
std::cout << "Have the same: " << (CheckConstructable<A, C, std::string>::value ? "yes" : "no") << "\n";
std::cout << "Have the same: " << (CheckConstructable<B, C, std::string, int>::value ? "yes" : "no") << "\n";
}