gpt4 book ai didi

c++ - 仅当没有其他转换可用时如何启用构造函数模板?

转载 作者:行者123 更新时间:2023-11-30 05:09:55 25 4
gpt4 key购买 nike

<分区>

下面的代码

#include <iostream>
#include <type_traits>

template <typename T>
struct bar {
bar(const bar<T>&) {
std::cout << "copy ctor\n";
}

template <typename U,
typename = std::enable_if_t<!std::is_convertible_v<U, bar<T>>>>
bar(U&&) {
std::cout << "ctor template\n";
}
};

struct foo {
operator bar<int>() const {
return bar<int>( 1 );
}
operator int() const {
return 2;
}
};

int main() {
foo my_foo;

std::cout << "constructor: ";
bar<int> my_bar( my_foo );

std::cout << "static_cast: ";
my_bar = static_cast<bar<int>>(my_foo);
}

produces

constructor: ctor template
static_cast: ctor template

作为输出。

但是我想要 bar 的构造函数模板,即 template <typename U> bar::bar(U&&) , 仅在 U 时启用尚未转换为 bar<T> .如果是foo foo::operator bar<int>() const 已经给出了这样的转换.假设我是 bar 的作者并且不知道(或影响)foo或可能的类似类(class)。我怎样才能说服编译器在这种情况下使用转换运算符而不删除 bar的 ctor 模板是否完整?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com