【问题标题】:Compile time check constructors with same signature编译时检查具有相同签名的构造函数
【发布时间】:2015-11-09 12:17:26
【问题描述】:

是否可以在编译时检查属于两个不同类的两个构造函数是否具有相同的签名? 如果可以,如何实现?

例子:

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;
}

【问题讨论】:

  • 请提供一些示例代码。你会如何使用这样的特质?
  • 尝试使用decltypethe type support functions 可能会奏效。
  • 你想如何处理默认参数?
  • 您永远无法获得该用法语法(也无法添加&amp;),因为构造函数没有名称(12.1 的第一句)。在 C++ 中,无论您在哪里命名构造函数,它实际上都是语法的一种特殊构造。没有这样的构造用于从构造函数创建指针或对成员函数的引用。
  • 现在,这并不能立即排除语法same_constructor_signatures&lt; A, B &gt;::value ...但是当您只有 SFINAE、没有指向成员函数的指针、没有类型时,检查签名非常困难推理或模板推导。

标签: c++ constructor compile-time


【解决方案1】:

是否可以在编译时检查属于两个不同类的两个构造函数是否具有相同的签名?

不完全是你想要的,但你可以检查class Aclass B是否可以 使用这种构造从相同的类型构造CheckConstructable&lt;A, B, types...&gt;::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";
}

【讨论】:

  • 很棒的代码,这可以部分解决问题,如果我能以某种可变参数的方式提取参数,例如“Args ...”或类似的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 2019-03-19
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多