我知道 C++ 在类型之间转换时只允许单个用户定义的隐式转换。然而,我最近遇到了一种情况,似乎在初始化时允许双重用户定义的隐式转换。
考虑以下类:
//fractions
class Rational {
public:
int num, den;
// default constructor, etc.
Rational(int n) : num(n), den(1) {} // NOT explicit
// arithmetic and compound assignment defined between two Rational's.
};
//numbers of the form a + b sqrt(N), where a, b are of type R
template<typename R, int N>
class RingExtension {
public:
R a, b;
// default constructor, etc.
RingExtension<R, N>(R a) : a(a), b(0) {} // NOT explicit
// arithmetic and …Run Code Online (Sandbox Code Playgroud) c++ standards-compliance type-conversion visual-c++ implicit-conversion
我正在用 C++14 绘制一个小的通用类型包装器模板,它旨在使用 mixins 启用、禁用或扩展底层类型的接口。
这是这个包装器的代码(精简了一点):
namespace detail {
/// Helper template that is forwarded to the mixins used
/// for the extension of wrapper<•> in order to enable
/// access to the actual type `Derived`
template <typename Derived>
struct Cast {
using type = Derived;
template <typename T>
static constexpr Derived& self(T* self) { return *static_cast<Derived*>(self); }
template <typename T>
static constexpr Derived const& self(T const* self) { return *static_cast<Derived const*>(self); }
};
/// This helper template is used …Run Code Online (Sandbox Code Playgroud) c++ constructor explicit-constructor implicit-conversion c++14
考虑这个接口和类......
public interface IValueHolder{}
public class ValueHolder<TValue> : IValueHolder {
public ValueHolder(TValue value) => this.value = value;
public TValue value { get; }
public static implicit operator ValueHolder<TValue>(TValue value) => new ValueHolder<TValue>(value);
public static implicit operator TValue(ValueHolder<TValue> valueHolder) => valueHolder.value;
}
class ValueStorage : Dictionary<string, IValueHolder>{}
Run Code Online (Sandbox Code Playgroud)
注意到和从的隐式转换TValue。
这段代码的重点是我试图存储键/值对,其中值可以是任何类型,但没有装箱惩罚。这是可能的,因为在设置或从存储中检索值时,我将始终知道类型。(这就是为什么我不只是使用Dictionary<string, object>.)
现在考虑这个代码......
var storage = new ValueStorage();
storage["UltimateQuestion"] = new ValueHolder<string>("What do you get when you multiply six by nine?");
storage["UltimateAnswer"] = new ValueHolder<int>(42);
var jsonSerializerSettings = new …Run Code Online (Sandbox Code Playgroud) 我一直在阅读各种来源,字符串文字在程序的整个生命周期中都保留在内存中。在那种情况下,这两个函数之间有什么区别
char *f1() { return "hello"; }
char *f2() {
char str[] = "hello";
return str;
}
Run Code Online (Sandbox Code Playgroud)
虽然f1编译正常,但f2抱怨我正在返回堆栈分配的数据。这里会发生什么?
str指向实际的字符串文字(具有静态持续时间),为什么会出现错误?str,那么原始字符串文字去哪里了?它是否保留在内存中而不引用它?考虑以下代码
#include <functional>
template<class ResultType, class ... Args>
void Foo( std::function<ResultType(Args...)> ) {}
void Dummy(int) {}
int main()
{
Foo<void, int> ( std::function<void(int)>( Dummy ) ); // OK, no deduction and no conversion
Foo( std::function<void(int)>( Dummy ) ); // OK, template argument deduction
Foo<void, int>( Dummy ); // Compile error
}
Run Code Online (Sandbox Code Playgroud)
在第三个中,我知道不能进行模板推导,这就是明确指定模板参数的原因。但是为什么没有从void (*)(int)to的显式转换std::function<void(int)>?
我查找了答案,但这些是关于模棱两可的重载解决方案或模板推论,而不是相关主题。
std::function 的模板参数(签名)不是其类型的一部分吗?
然后我尝试使用我自己的模板类而不是 std::function 进行测试。
// Variadic template class
template<class ... T>
class Bar
{ …Run Code Online (Sandbox Code Playgroud) c++ templates variadic-functions implicit-conversion variadic-templates
有人可以向我解释为什么会发生以下情况吗?
ifelse(TRUE, numeric(0), 1)
> [1] NA
Run Code Online (Sandbox Code Playgroud)
我当然希望数字(0)。我怀疑这是因为 ifelse 是矢量化的,例如以下作品,但我不明白到底发生了什么。
if (TRUE) numeric(0) else 1
#> numeric(0)
Run Code Online (Sandbox Code Playgroud) 这两个声明有什么区别:
double math_operation(double x, double (*func)(double));
double math_operation(double x, double func(double));
Run Code Online (Sandbox Code Playgroud)
它们似乎都在 GCC 中使用相同的调用:
math_operation(2.0, sqrt);
Run Code Online (Sandbox Code Playgroud)
它只是语法糖还是更多?
c function-pointers implicit-conversion function-declaration
长话短说:我想了解为什么在D::operator B() const下面代码的最后一行中没有使用转换运算符,因此在编译时失败g++ -std=c++17 source.cpp(g++ -std=c++2a deleteme.cpp尽管编译成功)。
错误是:
$ g++ -std=c++17 deleteme.cpp && ./a.out
In file included from /usr/include/c++/10.2.0/cassert:44,
from deleteme.cpp:1:
deleteme.cpp: In function ‘int main()’:
deleteme.cpp:19:14: error: no match for ‘operator==’ (operand types are ‘D’ and ‘B’)
19 | assert(d == B{2}); // conversion operator not invoked explicitly errors // LINE
| ~ ^~ ~~~~
| | |
| D B
In file included from /usr/include/c++/10.2.0/utility:70,
from deleteme.cpp:2:
/usr/include/c++/10.2.0/bits/stl_pair.h:466:5: note: candidate: ‘template<class _T1, …Run Code Online (Sandbox Code Playgroud) c++ type-conversion derived-class implicit-conversion std-pair
我正在尝试编写一个简单的类,该类complex<double>在需要复数的上下文中使用时将充当数字,否则它将充当 a double(要求虚部在以这种方式使用时必须为 0)
这是我到目前为止:
class Sample
{
public:
Sample() {}
Sample(double real) : m_data(real) {}
Sample(double real, double imaginary) : m_data(real, imaginary) {}
operator std::complex<double>() const
{
return m_data;
}
operator double() const
{
assert(m_data.imag() == 0.0);
return m_data.real();
}
private:
std::complex<double> m_data;
};
Run Code Online (Sandbox Code Playgroud)
这适用于大多数情况。每当这个类被传递给一个需要复数的函数时,它就会表现得好像它是一个复数。任何时候它被传递给一个需要 double 的函数,它会表现得好像它是一个 double。
当我将它传递给一个接受复数和双精度数的函数时,问题就出现了。(例如std::arg)。当我尝试将Sample对象传递给std::arg它时,它不知道要使用哪种转换,因为两者在技术上都是有效的。
在这种情况下,我希望complex转换为“首选”,并将其作为复合体传递。当两种转换在技术上都可以接受时,有没有办法让一个用户定义的函数优先于另一个?
我知道类型化指针void*在传递给需要void*参数的函数时可以隐式转换,但我没想到会在三元操作中看到它(至少我认为这是怎么回事)。
考虑这个简化的代码:
int * dude() {
float * f = NULL;
int * i = NULL;
return (0 ? f : i); // pointer type mismatch in conditional expression (good: this is what I want)
}
Run Code Online (Sandbox Code Playgroud)
但如果我投i给void*:
int * dude() {
float * f = NULL;
int * i = NULL;
return (0 ? f : (void*)i); // no error! it suddenly likes f? or is f being optimized out?
}
Run Code Online (Sandbox Code Playgroud)
我会更进一步,故意返回 …
c pointers conditional-operator language-lawyer implicit-conversion
c++ ×5
c ×3
arrays ×1
c# ×1
c++14 ×1
constructor ×1
if-statement ×1
json.net ×1
pointers ×1
r ×1
std-pair ×1
templates ×1
visual-c++ ×1