在我的设置中,我试图有一个Table继承自的接口Map(因为它主要用作地图的包装器)。两个类继承自Table- 本地和全局。全局的将有一个可变的映射,而本地的将有一个只有本地条目的映射。
// entries
sealed class Entry {
class EntryLocal : Entry
class EntryGlobal : Entry
}
interface Table : Map<String, Entry> {
fun getRecursive(key: String): Entry?
}
class GlobalTable(val map:MutableMap<String, Entry>) : Table, Map<String, Entry> by map {
override fun getRecursive(key: String) = this[key]
...
}
class LocalTable(
private val parent: Table,
val map: Map<String, EntryLocal>
) : Table, Map<String, EntryLocal> { // gives error
override fun getRecursive(key: String): Entry? = map[key] ?: …Run Code Online (Sandbox Code Playgroud) 在下面的代码示例中,我们有两个类X和Y,两者都可以隐式转换为n1::Base。Base支持加法,所以我认为X也Y应该通过转换为Base. 相反,他们仅在其模板参数是时才支持它Base(即使该模板参数未在任何地方使用)。
谁能解释这是为什么吗?如果您能给我指出该标准的一部分或链接相关的 cppreference.com 文章,我会加分。
X如果和Y全部支持加法或不支持加法,这对我来说将是直观的。但我不明白为什么它们只使用适当的模板参数进行编译。如果您不确定为什么这让我感到困惑,我很乐意为您提供更多说明。我猜它与 ADL(参数相关查找)有关,但我不确定。
Godbolt 链接:https://godbolt.org/z/xe3enE9Tf
代码:
#include <iostream>
namespace n1 {
struct Base {};
int operator+(Base const&, int other) { return other; }
}
using n1::Base;
// Uncommenting this would fix the error below.
// using n1::operator+;
template <class = Base>
struct X {
Base b;
operator Base() { return b; }
};
template …Run Code Online (Sandbox Code Playgroud)