具有特定接口的类型的C ++模板专业化

时间:2017-07-14 05:38:46

标签: c++ templates template-specialization

假设我有这样的模板:

template<class T>
class A
{
   ...
};

我希望这个模板只有在代替T代替的类型具有特定接口时才可以专用。例如,此类型必须具有以下两种方法:

int send(const char* buffer, size_t size);
int receive(char* buffer, size_t size);

如何对模板进行此限制? 谢谢你的帮助!

UPD:

这个问题是关于SFINAE?不是关于内在或阶级设计。

3 个答案:

答案 0 :(得分:5)

非常简单的方法是在T::send中使用T::receiveA,任何未实现这些的类型都会导致编译时失败以实例化模板。您只需要SFINAE来区分模板的特化。

e.g。

template<class T>
class A
{
    void useT(T & theT)
    {
        char buf[20]
        theT.send("Some Thing", 11);
        theT.recieve(buf, 20);
    }
};

答案 1 :(得分:1)

另一个答案显然是可取的,但既然您明确要求SFINAE,请转到:

L1 <- list("names" = list("first" = c("john","lisa","anna","mike","steven"),"last" = c("johnsson","larsson","johnsson","catell","larsson")),"stats" = list("physical" = list("age" = c(14,22,53,23,31), "height" = c(165,176,179,182,191)), "mental" = list("iq" = c(102,104,99,87,121))))

L2 <- list("johnsson" = list("names" = list("first" = c("john","anna")),"stats" = list("physical" = list("age" = c(14,53), "height" = c(165,179)), "mental" = list("iq" = c(102,99)))), "larsson" = list("names" = list("first" = c("lisa","steven")),"stats" = list("physical" = list("age" = c(22,31), "height" = c(176,191)), "mental" = list("iq" = c(104,121)))), "catell" = list("names" = list("first" = "mike"),"stats" = list("physical" = list("age" = 23, "height" = 182), "mental" = list("iq" = 87))))

L3 <- list("1" = list("names" = list("first" = c("john","lisa","mike"),"last" = c("johnsson","larsson","catell")),"stats" = list("physical" = list("age" = c(14,22,23), "height" = c(165,176,182)), "mental" = list("iq" = c(102,104,87)))), "2" = list("names" = list("first" = c("anna","steven"),"last" = c("johnsson","larsson")),"stats" = list("physical" = list("age" = c(53,31), "height" = c(179,191)), "mental" = list("iq" = c(99,121)))))

# make L2
foo <- function(x, idx) {

    if (is.list(x)) {
        return(lapply(x, foo, idx = idx))
    }
    return(x[idx])
}

levels <- unique(L1$names$last)
L2_2 <- vector("list", length(levels))
names(L2_2) <- levels
for (i in seq_along(L2_2)) {

    idx <- L1$names$last == names(L2_2[i])
    L2_2[[i]] <- list(names = foo(L1$names[-2], idx),
                      stats = foo(L1$stats, idx))

}
identical(L2, L2_2)

str(L2)
str(L2_2)

# make L3

dups <- duplicated(L1$names$last)
L3_2 <- vector("list", 2)
names(L3_2) <- 1:2
for (i in 1:2) {

    if (i == 1)
        idx <- !dups
    else
        idx <- dups

    L3_2[[i]] <- foo(L1, idx)

}
identical(L3, L3_2)
str(L3)
str(L3_2)

答案 2 :(得分:0)

检查类是否具有特定签名的方法是SFINAE原则的常见应用。例如,您可以查看therethere